from rest_framework import serializers
from rest_framework.serializers import StringRelatedField

# class StudentSerializer(serializers.Serializer):#序列化器 abc.ABC
#     # 类属性返回字段数据和数据的校验
#     id=serializers.IntegerField(label='ID',read_only=True) #read_only=True 只读
#     name = serializers.CharField(max_length=20, label='姓名')
#     age = serializers.IntegerField(label='年龄',required=False) #required=False 非必填字段
#     sex = serializers.IntegerField(label='性别')
#     c_time = serializers.DateTimeField(label='创建时间')
#     u_time = serializers.DateTimeField(label='修改时间')
#     is_delete = serializers.BooleanField(label='逻辑删除')
#
from apps.study.models import Student, Classes


class StudentSerializer(serializers.ModelSerializer):
    # 自定义字段
    # classes =StringRelatedField(read_only=True) # 一般不会直接覆盖原字段
    class_name=serializers.CharField(read_only=True,source='classes.name')
    class Meta:
        model = Student
        fields = '__all__'

        #年龄0<age<200
        extra_kwargs={
            'age':{
                'min_value':0,
                'max_value':200
            }

        }
    #自定义校验方法，对指定属性值进行校验
    # def validate_name(self,value):
    #     if 'python' not in value.lower():
    #         raise serializers.ValidationError('name error')
    #     return value

    # 自定义校验方法：获取所有属性的值
    # def validate(self, attrs):
    #     if 'python' not in attrs['name'].lower():
    #         raise serializers.ValidationError('name error')
    #     return attrs

class SimpleStudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id','name']

class ClassSerializer(serializers.ModelSerializer):
    # 自定义字段
    student_set = SimpleStudentSerializer(read_only=True,many=True)

    class Meta:
        model= Classes
        fields ='__all__'

    def validate_name(self,value):
        if 'python' not in value:
            raise  serializers.ValidationError('班级名必须带python')
        return value
